#define _CRT_SECURE_NO_WARNINGS 1

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void Ancestor(TreeNode* root, TreeNode* p, stack<TreeNode*>& stp)
    {
        if (root == nullptr)
            return;

        if (root == p)
        {
            stp.push(root);
            return;
        }
        stp.push(root);
        Ancestor(root->left, p, stp);
        if (stp.top() == p)
            return;
        Ancestor(root->right, p, stp);
        if (stp.top() == p)
            return;
        stp.pop();
    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        stack<TreeNode*> stp;
        stack<TreeNode*> stq;

        Ancestor(root, p, stp);
        Ancestor(root, q, stq);
        cout << stp.size() << ' ' << stq.size() << endl;

        while (stp.top() != stq.top())
        {
            if (stp.size() > stq.size())
                stp.pop();
            else if (stp.size() < stq.size())
                stq.pop();
            else
            {
                stq.pop();
                stp.pop();
            }
        }
        return stp.top();
    }
};